# -*- coding:utf-8 -*
import os
if os.name != 'nt':  # linux下使用epoll模式
    from twisted.internet import epollreactor
    epollreactor.install()
else:
    from twisted.internet import iocpreactor
    iocpreactor.install()

from twisted.internet import reactor, defer
from twisted.internet.protocol import ServerFactory, Protocol
from twisted.python import log
from server.util import errors, unPack, socketTin
import hmac, threading, time, datetime, Handler, mysql, cache, Filter


class serverProtocol(Protocol):
    def __init__(self):
        pass

    # @logs.logged("INFO")
    def send_Data(self, data):
        log.msg("send data: %s" % data)
        log.msg("------------------------request end-----------------------------------")
        self.transport.write(data)

    # @logs.logged("INFO")
    def connectionMade(self):
        self.unpack = unPack.unPack(self)  # 新建防粘包缓冲区
        log.msg("Connection %s" % self.transport.getPeer())

    # @logs.logged("INFO")
    def connectionLost(self, reason):
        pass

    # @logs.logged("INFO")
    def dataReceived(self, data):
        log.msg("------------------------request start %s-----,%s------------------------------" % (self.factory.num, self.transport.getPeer()))
        log.msg(data)
        # self.send_Data("[{'user': '123', 'password': '321'}, {'user': '773', 'password': '881'}]")
        # self.transport.loseConnection()
        self.factory.num += 1
        self.unpack.unpackage(data)


class serverFactory(ServerFactory):
    protocol = serverProtocol

    def __init__(self, fil, tin):
        self.filiter = fil
        self.tin = tin
        self.num = 0


def makeInit(parm):
    db = mysql.DBService()  # mysqldb
    re = cache.re(parm['redisParm']).redis  # redis
    tin = socketTin.socketTin()  # socket容器

    # Service
    handler = Handler.serviceHandler(re, db, tin)
    fil = Filter.serviceFilter(handler, tin)
    factory = serverFactory(fil, tin)  # Protocol factory

    return factory


# @logs.logged('info')
def begin():
    parm = {'tcpPort': 2111,
            'serviceIface': '',
            'redisParm': ('127.0.0.1', 6379, 0),
            'mysqlDBParm': ('192.168.1.5', 3306, 'root', 'w111111', 'RWLS', 'utf8'),
            'mongoDBUri': 'mongodb://127.0.0.1'}

    # TODO log to mongodb
    log.startLogging(open(r"server/logs/call.log", 'w'))  # log

    factory = makeInit(parm)

    reactor.listenTCP(parm['tcpPort'], factory, interface=parm['serviceIface'])
    reactor.run()

